#include "historymessagewidget.h"
#include"model/datacenter.h"

HistoryMessageWidget::HistoryMessageWidget(QWidget *parent)
    :QDialog(parent)
{
    // 1. 设置⾃⾝属性.
    this->setFixedSize(600, 600);
    this->setWindowTitle("历史消息");
    this->setWindowIcon(QIcon(":/images/logo.png"));
    // 设置关闭后⾃动销毁
    this->setAttribute(Qt::WA_DeleteOnClose);
    // 设置背景⾊
    this->setStyleSheet("QWidget { background-color: rgb(255, 255, 255); } ");

    // 2. 创建核⼼布局
    QGridLayout* layout = new QGridLayout();
    layout->setContentsMargins(30, 30, 30, 30);
    layout->setSpacing(10);
    this->setLayout(layout);

    // 创建单选框
    radioBtn1 = new QRadioButton();
    radioBtn2 = new QRadioButton();
    radioBtn1->setText("按关键词查询");
    radioBtn2->setText("按时间查询");
    layout->addWidget(radioBtn1, 0, 0, 1, 2);
    layout->addWidget(radioBtn2, 0, 2, 1, 2);
    radioBtn1->setChecked(true); // 默认按关键词查询

    // 3. 创建搜索框
    searchEdit = new QLineEdit();
    searchEdit->setFixedHeight(50);
    searchEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    searchEdit->setPlaceholderText("要搜索的关键字");
    searchEdit->setStyleSheet("QLineEdit { border-radius: 10px; backgroundcolor: rgb(243, 243, 243);\
                                border: none; padding-left: 10px; font-size: 16px;}");

    // 搜索框横跨 8 列
    layout->addWidget(searchEdit, 1, 0, 1, 8);

    // 4. 创建搜索按钮
    searchBtn = new QPushButton();
    searchBtn->setFixedSize(50, 50);
    searchBtn->setIcon(QIcon(":/images/search.png"));
    searchBtn->setIconSize(QSize(30, 30));
    QString style = "QPushButton { background-color: rgb(243, 243, 243); border: none; border-radius: 10px;}";
    style += "QPushButton:hover {background-color: rgb(219, 219, 219);}QPushButton:pressed {background-color: rgb(206, 206, 206);}";
    searchBtn->setStyleSheet(style);

    // 搜索按钮占 1 ⾏
    layout->addWidget(searchBtn, 1, 8, 1, 1);

    // 5. 创建⽇期选择器
    begLabel = new QLabel();
    begLabel->setText("开始时间");
    endLabel = new QLabel();
    endLabel->setText("结束时间");
    begTimeEdit = new QDateTimeEdit();
    endTimeEdit = new QDateTimeEdit();

    auto endDateTime = QDateTime::currentDateTime();
    auto beginDateTime = endDateTime.addDays(-30);

    begTimeEdit->setDateTime(beginDateTime);
    endTimeEdit->setDateTime(endDateTime);
    begTimeEdit->setFixedHeight(40);
    endTimeEdit->setFixedHeight(40);

    // 初始情况隐藏.
    begLabel->hide();
    endLabel->hide();
    begTimeEdit->hide();
    endTimeEdit->hide();

    // 6. 创建历史消息显⽰区域
    QScrollArea* scrollArea = initScrollArea();
    // 直接占据 9 列.
    layout->addWidget(scrollArea, 2, 0, 1, 9);

    // 7. 实现切换搜索模式
    connect(radioBtn1, &QRadioButton::clicked, this, [=]() {
        layout->removeWidget(begLabel);
        layout->removeWidget(endLabel);
        layout->removeWidget(begTimeEdit);
        layout->removeWidget(endTimeEdit);

        begLabel->hide();
        endLabel->hide();
        begTimeEdit->hide();
        endTimeEdit->hide();
        layout->addWidget(searchEdit, 1, 0, 1, 8);
        searchEdit->show();
    });

    connect(radioBtn2, &QRadioButton::clicked, this, [=]() {
        layout->removeWidget(searchEdit);
        searchEdit->hide();

        layout->addWidget(begLabel, 1, 0, 1, 1);
        layout->addWidget(begTimeEdit, 1, 1, 1, 3);
        layout->addWidget(endLabel, 1, 4, 1, 1);
        layout->addWidget(endTimeEdit, 1, 5, 1, 3);

        begLabel->show();
        endLabel->show();
        begTimeEdit->show();
        endTimeEdit->show();
    });

// 8. 添加数据
#if TEST_UI
    QString text = "很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消\
                    息很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消\
                    息很⻓的消息很⻓的消息很⻓的消息很⻓的消息很⻓的消息";
    model::UserInfo sender;
    sender.avatar = QIcon(":/images/default_avatar.jpg");
    sender.description = "此行又山高路远";
    sender.nickname = "张三";
    sender.phone = "123445678900";

    for (int i = 0; i < 30; i++) {
        sender.userId = QString::number(i);
        model::Message message = model::Message::makeMessage(model::TEXT_TYPE, QString::number(i), sender, QString("测试消息").toUtf8(),"");
        addHistoryMessage(message);
    }
#endif

#if LOAD_DATA_FROM_NETWORK
    connect(searchBtn, &QPushButton::clicked, this, &HistoryMessageWidget::clickSearchBtn);
#endif

}

QScrollArea *HistoryMessageWidget::initScrollArea()
{
    // 创建成员列表区
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    // ⼀定要添加这个设置, 否则⽆法正确显⽰.
    scrollArea->setWidgetResizable(true);

    // 隐藏⽔平滚动条. 把垂直滚动条设置的细⼀些.
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical {width: 2px; background-color: rgb(255, 255, 255); }\
                                                    QScrollBar::handle:vertical {background-color: rgb(205, 205, 205);}");
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal {height: 0px;}");

    scrollArea->setStyleSheet("QScrollArea { border: none;}");
    container = new QWidget();
    scrollArea->setWidget(container);

    QVBoxLayout* layout = new QVBoxLayout();
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);
    container->setLayout(layout);

    return scrollArea;
}

void HistoryMessageWidget::clear()
{
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(container->layout());
    for (int i = layout->count() - 1; i >= 0; --i) {
        QWidget* w = layout->itemAt(i)->widget();
        if (w == nullptr) {
            continue;
        }
        layout->removeWidget(w);
        delete w;
    }
}

void HistoryMessageWidget::addHistoryMessage(const model::Message& message)
{
    HistoryMessageItem* item = HistoryMessageItem::makeHistoryMessageItem(message);
    container->layout()->addWidget(item);
}

void HistoryMessageWidget::clickSearchBtn()
{
    //清空原有的内容
    this->clear();

    // 1. 处理响应
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    connect(dataCenter, &model::DataCenter::searchMessageDone, this, &HistoryMessageWidget::clickSearchBtnDone);

    if (radioBtn1->isChecked()) {
        // 2. 按照词查询. 获取到输⼊框的查询词
        const QString& searchKey = searchEdit->text();
        if (searchKey.isEmpty()) {
            return;
        }
        // 3. 发送请求
        dataCenter->searchMessageAsync(searchKey);
    }
    else {
        // 按照时间搜索, 获取输⼊框的时间⽇期
        auto begTime = begTimeEdit->dateTime();
        auto endTime = endTimeEdit->dateTime();

        if(begTime >= endTime){
            LOG() << "时间错误! 开始时间⼤于等于结束时间!";
            return;
        }

        dataCenter->searchMessageByTimeAsync(begTime, endTime);
    }
}

void HistoryMessageWidget::clickSearchBtnDone()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    // 1. 获取到搜索结果列表
    QList<model::Message>* searchMessageResult = dataCenter->getSearchMessageResult();
    if (searchMessageResult == nullptr) {
        LOG() << "获取搜索结果为空";
        return;
    }

    // 2. 清空已有列表内容
    this->clear();
    // 3. 添加响应结果的内容
    for (const auto& message : *searchMessageResult) {
        this->addHistoryMessage(message);
    }

}

HistoryMessageItem::HistoryMessageItem()
{}

HistoryMessageItem *HistoryMessageItem::makeHistoryMessageItem(const model::Message &message)
{
    // 1. 设置核⼼属性
    HistoryMessageItem* item = new HistoryMessageItem();
    item->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    // 2. 创建主布局
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setContentsMargins(0, 0, 0, 0);
    gridLayout->setSpacing(10);
    item->setLayout(gridLayout);

    // 3. 创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40, 40);
    avatarBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    avatarBtn->setIconSize(QSize(40, 40));
    avatarBtn->setIcon(message.sender.avatar);
    avatarBtn->setStyleSheet("QPushButton { border: none; }");

    // 4. 创建名字 + 时间
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(message.sender.nickname + " | " + message.time);
    nameLabel->setFixedHeight(20);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 5. 创建消息体
    QWidget* contentWidget = nullptr;
    if (message.messageType == model::TEXT_TYPE) {
        QLabel *label = new QLabel();
        label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        // 设置⼤⼩策略
        label->setWordWrap(true); // 启⽤⽂本换⾏
        label->adjustSize(); // 调整⼤⼩以适应内容
        label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
        label->setText(QString(message.content));
        contentWidget = label;
    // else if (message.messageType == IMAGE_TYPE) {
    //     contentWidget = new ImageButton(message.fileId, message.content);
    // } else if (message.messageType == FILE_TYPE) {
    //     contentWidget = new FileLabel(message.fileId, message.content,
    //                                   message.fileName);
    // } else if (message.messageType == SPEECH_TYPE) {
    //     contentWidget = new SoundLabel(message.fileId, message.content);
    } else {
        LOG() << "错误的 messageType = " << message.messageType;
    }

    // 6. 把上述控件放⼊布局中.
    gridLayout->addWidget(avatarBtn, 0, 0, 2, 1);
    gridLayout->addWidget(nameLabel, 0, 1, 1, 1);
    // 这⾥先设置占 5 ⾏
    gridLayout->addWidget(contentWidget, 1, 1, 5, 1);
    return item;
}
